<?php

/*微信接口*/

class Wechat
{
    private static $token = 'Token1';
    private static $appID = 'wxb56bc1c1ee0e0770';
    private static $appsecret = '192ade8f94afe264b51b2e3cd151161e';

    //配置验证服务器token
    public static function valid()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = self::$token;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);
        if ($tmpStr == $signature) {
            echo $_GET["echostr"];
        }
    }

    //接收微信消息
    public static function getWechatObj()
    {
        //微信服务器返回给业务服务器的xml字符串
        $xml = file_get_contents('php://input');

        if ($xml) {
            //addlog($xml);
            //把xml变成对象
            return simplexml_load_string($xml, 'simpleXMLElement', LIBXML_NOCDATA);
        }
    }

    //判断用户是否是订阅
    public static function isSubscribe()
    {
        $obj = self::getWechatObj();
        if ($obj->MsgType == 'event') {
            if ($obj->Event == 'subscribe') {
                return true;
            }
        }
        return false;
    }

    //判断用户是否是菜单点击
    public static function isEventKey()
    {
        $obj = self::getWechatObj();
        if ($obj->MsgType == 'event') {
            if ($obj->Event == 'CLICK') {
                return true;
            }
        }
        return false;
    }

    //获取菜单点击类型的值
    public static function getClickKey()
    {
        $obj = self::getWechatObj();
        return $obj->EventKey;
    }


    //回复文本消息
    public static function replyMsg($msg)
    {
        $obj = self::getWechatObj();
        //刚才是用户发给我们，现在是我们发给用户，所以反转下
        //我们变成发送者FromUserName，⽤户变为接收者ToUserName
        $FromUserName = $obj->ToUserName;
        $ToUserName = $obj->FromUserName;
        $CreateTime = time();
        $MsgType = 'text';
        $Content = $msg;
        //3.组合要回复的模板
        $template = <<<str
            <xml>
            <ToUserName><![CDATA[{$ToUserName}]]></ToUserName>
            <FromUserName><![CDATA[{$FromUserName}]]></FromUserName>
            <CreateTime>{$CreateTime}</CreateTime>
            <MsgType><![CDATA[{$MsgType}]]></MsgType>
            <Content><![CDATA[{$Content}]]></Content>
            </xml>
str;
        echo $template;
        exit;
    }

    //回复图文消息
    public static function replyNews($data)
    {
        $obj = self::getWechatObj();
        //刚才是⽤户发给我们，现在是我们发给⽤户，所以反⼀下
        //我们变成发送者FromUserName，⽤户变为接收者ToUserName
        $FromUserName = $obj->ToUserName;
        $ToUserName = $obj->FromUserName;
        $CreateTime = time();
        $MsgType = 'news';
        //设置回复内容
        $template = "<xml>
		<ToUserName><![CDATA[{$ToUserName}]]></ToUserName>
		<FromUserName><![CDATA[{$FromUserName}]]></FromUserName>
		<CreateTime>{$CreateTime}</CreateTime>
		<MsgType><![CDATA[{$MsgType}]]></MsgType>
		<ArticleCount>" . count($data) . "</ArticleCount>
		<Articles>";

        //循环数据，组合xml
        foreach ($data as $v) {
            $template .= "<item>
			<Title><![CDATA[{$v['title']}]]></Title>
			<Description><![CDATA[{$v['description']}]]></Description>
			<PicUrl><![CDATA[{$v['picurl']}]]></PicUrl>
			<Url><![CDATA[{$v['url']}]]></Url>
			</item>";
        }
        $template .= "</Articles></xml>";
        exit($template);
    }

    //获得用户输入的内容
    public static function getContent()
    {
        $obj = self::getWechatObj();
        return trim($obj->Content);
    }

    /***************************    API     ****************************/

    //获取token
    public static function getAccessToken()
    {
        //保存access_token的缓存文件
        $atFile = './cache/at.php';
        //如果存access_token的文件存在并且没有过期
        if (is_file($atFile) && filemtime($atFile) + 7200 > time()) {
            $atArr = include $atFile;
            return $atArr['access_token'];
        }
        //请求地址
        $url = "https://api.weixin.qq.com/cgi-bin/token";
        //获取access_token填写client_credential
        $grant_type = 'client_credential';
        //第三⽅⽤户唯⼀凭证
        $appid = self::$appID;
        //第三⽅⽤户唯⼀凭证密钥，即appsecret
        $secret = self::$appsecret;
        //最终地址
        $url .= "?grant_type={$grant_type}&appid={$appid}&secret={$secret}";
        //请求微信服务器要回复access_token
        $curl = new Curl\Curl();
        $json = $curl->get($url);

        //把返回的json转为数组
        $arr = json_decode($json->response, true);
        file_put_contents($atFile, "<?php return " . var_export($arr, true) . ";");
        return $arr['access_token'];
    }

    //获取jssdk_ticket
    public static function getJsapiTicket()
    {
        $tkfile = './cache/tk.php';
        if (is_file($tkfile) && fileatime($tkfile) + 7200 > time()) {
            $ticketArr = include($tkfile);
            return $ticketArr['ticket'];
        }
        $url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=' . self::getAccessToken() . '&type=jsapi';
        $curl = new Curl\Curl();
        $json = $curl->get($url);
        $arr = json_decode($json->response, true);
        file_put_contents($tkfile, "<?php return " . var_export($arr, true) . "; ?>");
        return $arr['ticket'];

    }

    //获取微信ip
    public static function getIps()
    {
        //调用微信服务器的ip
        $accessToken = self::getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token=";
        $url .= $accessToken;
        //调取接⼝
        $curl = new Curl\Curl();
        $data = $curl->get($url);
        return $data->response;
    }

    //配置微信菜单
    public static function createMenu($data)
    {
        $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" . self::getAccessToken();
        $curl = new Curl\Curl();
        $res = $curl->post($url, $data);
        return $res;
    }


}

?>